package com.dqp.cslggroup.ZCJXJ;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.InputType;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import androidx.preference.PreferenceManager;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.dd.morphingbutton.impl.IndeterminateProgressButton;
import com.dqp.cslggroup.Api.appApi;
import com.dqp.cslggroup.Api.comprehensiveTestApi;
import com.dqp.cslggroup.ConnectSever.SeverIP;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.ProgressButton.LinearProgressButtonUtil;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.Util.*;
import com.dqp.cslggroup.bean.Club;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Map;

import static com.dqp.cslggroup.UI.MyApplication.getContext;

public class XSGZ_login extends BaseActivity {
    private String url = "http://xsgz.cslg.edu.cn", zc, jxj, use_url, yzm;
    private Map<String, String> cookies;
    private EditText userin;
    private EditText pwdin;
    private String stuNum = null;
    private String password = null;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private TextView tip;
    private ImageView yz_img;
    private EditText yz;
    private int flag = 1;
    private RadioButton nei, wai;
    private LinearLayout root_view;
    private int vpn = 1;
    private IndeterminateProgressButton btnMorph1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_jwxt);
        EventBus.getDefault().register(this);
        initComp();
//        selLoginImg("xsgl");
        rem_password();
        selectUrl();
        UiUtils.addLayoutListener(root_view, tip);
        if (NetCheckUtil.checkNet(XSGZ_login.this))
            initFunc();
        else ToastUtil.showToast("请连接网络！");
    }

    public void selLoginImg(String stype) {
        new Thread(() -> {
            Club club;
            ArrayList<Club> dataList = appApi.getLoginImg();
            for (int i = 0; i < dataList.size(); i++) {
                club = dataList.get(i);
                if (club.getClub_des().equals(stype)) {
                    EventBus.getDefault().post(new MessageEvent("XSGZ_login", 2, club));
                }
            }
        }).start();
    }


    private void selectUrl() {
        if (nei.isChecked())
            vpn = 0;
        else if (wai.isChecked()) {
            vpn = 1;
        }
    }

    public void rem_password() {
        sp = PreferenceManager.getDefaultSharedPreferences(XSGZ_login.this);
        pwdin.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        boolean isRemember = sp.getBoolean("remember_XSGZ_password", false);
        if (isRemember) {
            stuNum = sp.getString("stuNum_XSGZ", "");
            password = sp.getString("password_XSGZ", "");
            userin.setText(stuNum);
            pwdin.setText(password);
            editor = sp.edit();
            editor.putBoolean("remember_XSGZ_password", true);
            editor.putString("stuNum_XSGZ", stuNum);
            editor.putString("password_XSGZ", password);
            editor.apply();
        }
    }

    private void initComp() {
        userin = findViewById(R.id.jwxt_username);
        pwdin = findViewById(R.id.jwxt_password);
        LinearLayout relativeLayout = findViewById(R.id.jwxt_yz_rel);
        relativeLayout.setVisibility(View.VISIBLE);
        TextView tishi = findViewById(R.id.jwxt_frag_tv_tishi);
        tishi.setVisibility(View.GONE);
        tip = findViewById(R.id.jwxt_frag_tv_tip);
        nei = findViewById(R.id.jwxt_nei);
        wai = findViewById(R.id.jwxt_wai);
        tip.setText("初始密码为身份证后六位");
        yz = findViewById(R.id.jwxt_yz);
        yz_img = findViewById(R.id.jwxt_verimg);
        RadioGroup radioGroup = findViewById(R.id.wang);
        root_view = findViewById(R.id.root_view);
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (nei.isChecked()) {
                use_url = url;
            } else if (wai.isChecked()) {
                SharedPreferences sp;
                SharedPreferences.Editor editor;
                sp = PreferenceManager.getDefaultSharedPreferences(XSGZ_login.this);
                editor = sp.edit();
                String ip = sp.getString("ip", SeverIP.getIp().getString("ip"));
                editor.apply();
                use_url = ip + ":8882";
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private void initFunc() {
//        new PicThread().start();
        InputMethodManager manager = ((InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE));
        btnMorph1 = findViewById(R.id.btnMorph);
        LinearProgressButtonUtil progressButtonUtil = new LinearProgressButtonUtil(getContext());
        progressButtonUtil.IPBmorphToSquare(btnMorph1, 0);
        btnMorph1.setOnClickListener(view -> {
            stuNum = userin.getText().toString().replace(" ", "");
            password = pwdin.getText().toString().replace(" ", "");
            yzm = yz.getText().toString().replace(" ", "");
            if (stuNum == null || stuNum.length() < 8 || yz == null || yz.length() < 4 || password == null || password.length() < 5)
                ToastUtil.showToast("请输入正确学号、密码、验证码！");
            else {
                if (manager != null)
                    manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                if (btnMorph1.getText().equals("登录")) {
                    progressButtonUtil.IPBonMorphButtonClicked(btnMorph1);
                    String result = stuNum.substring(stuNum.length() - 5, stuNum.length() - 3);
                    String year = String.valueOf(GetTimeUtil.getYear());
                    if (!year.contains(result)) {
                        new Thread(this::login).start();
                    } else setTip();
                } else {
                    progressButtonUtil.IPBmorphToSquare(btnMorph1, progressButtonUtil.integer(R.integer.mb_animation));
                }
            }
        });
//        yz_img.setOnClickListener(view -> new PicThread().start());
    }

    public void setTip() {
        com.dqp.cslggroup.UI.AlertDialog alertDialog = new com.dqp.cslggroup.UI.AlertDialog(this);
        alertDialog.builder();
        alertDialog.setGone()
                .setTitle("告知新生")
                .setMsg("综测成绩是总评上一学期或上一学年的综测表现，" +
                        "刚入学的大一新生第一学期没有综测成绩，" +
                        "所以系统并没有你的数据，" +
                        "目前大一新生第一学期无法使用该功能！" +
                        "请谅解！")
                .setNegativeButton("朕已阅", R.color.colorAccent, null)
                .show();
    }

    public void login() {
        JSONObject jsonObject = comprehensiveTestApi.login(stuNum, password);
        if (Result.jsonResultIsTure(jsonObject)) {
            UiUtils.startActivity(this, XSGZ_main.class);
        } else ToastUtil.showToast(jsonObject.getString("resultMsg"));
    }

//    public class PicThread extends Thread {
//        @Override
//        public void run() {
//            Connection.Response response;
//            try {
//                response = Jsoup.connect(use_url + "/jeesite/a/academic/zcAchievement")
//                        .ignoreContentType(true)
//                        .userAgent("Mozilla")
//                        .method(Connection.Method.GET)
//                        .header("Authorization", Authorization)
//                        .timeout(5000)
//                        .execute();
//                cookies = response.cookies();
//
//                response = Jsoup.connect(use_url + "/jeesite/servlet/validateCodeServlet")
//                        .cookies(cookies)
//                        .ignoreContentType(true)
//                        .userAgent("Mozilla")
//                        .method(Connection.Method.GET)
//                        .header("Authorization", Authorization)
//                        .timeout(5000)
//                        .execute();
//                byte[] bytes = response.bodyAsBytes();
//                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//                EventBus.getDefault().post(new MessageEvent("XSGZ_login", 3, bitmap));
//                flag = 1;
//            } catch (IOException e) {
//                e.printStackTrace();
//                flag = 0;
//                ToastUtil.showToast("验证码获取失败！");
//
//            }
//        }
//    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("XSGZ_login")) {
            if (event.getWhat() == 0) {
                LinearProgressButtonUtil buttonUtil = new LinearProgressButtonUtil(this);
                buttonUtil.IPBmorphToSuccess(btnMorph1);
                finish();
                Intent intent = new Intent(XSGZ_login.this, XSGZ_main.class);
                if (zc.length() > 0) {
                    intent.putExtra("zc", zc);
                    intent.putExtra("jxj", jxj);
                }
                startActivity(intent);
            }
            if (event.getWhat() == 1) {
                LinearProgressButtonUtil buttonUtil = new LinearProgressButtonUtil(this);
                buttonUtil.IPBmorphToFailure(btnMorph1, buttonUtil.integer(R.integer.mb_animation));
                if (event.getMessage() != null)
                    ToastUtil.showToast(event.getMessage());
                else ToastUtil.showToast("登陆失败！");
            }
            if (event.getWhat() == 2) {
                ImageView bg = findViewById(R.id.jwxt_img);
                TextView title = findViewById(R.id.jwxt_img_title);
                Club club = (Club) event.getObj();
                title.setText(club.getClub_name());
                Glide.with(XSGZ_login.this).load(club.getClub_img()).into(bg);
            }
            if (event.getWhat() == 3) {
                yz_img.setImageBitmap((Bitmap) event.getObj());
            }
        }


    }

}
